var pipe = null;
function download_music_back(music_url, name) {
    if(pipe){
        pipe.postMessage({'music_url':music_url, 'name':name});
    }
}
function getStorage(key){
    chrome.storage.local.get(["key"]).then((result) => {
    });
}
// 下载歌曲
/*bitrate
lMusic: 96000
mMusic: 160000
hMusic: 320000
bMusic: best
*/
function start_download_music(music_id, music_type, bitrate, filename_format, download_music) {
    var url = '';
    if(music_type == 'song') {
        url = 'http://music.163.com/api/song/detail?ids=[' + music_id + ']';
    }else {
        url = 'http://music.163.com/api/dj/program/detail?id=' + music_id;
    }
    $.get(url, function(result) {
        resp = JSON.parse(result);
        //document.getElementById("auto-id-LwQgHJJCyUfPGcw").append(result);
        if(resp['code'] == 200) {
            var song = null;
            if(music_type == 'song') {
                song = resp['songs'][0];
            } else {
                song = resp['program']['mainSong'];
            }
            var music = song[bitrate];
            if(music == null) {
                music = song['bMusic'];
            }
            var filename = filename_format.replace('$album', song['album']['name']);
            filename = filename.replace('$song', song['name']);
            filename = filename.replace('$artist', song['artists'][0]['name']);
            filename = filename.replace(new RegExp('/|\\\\|\\:|\\*|\\?|"|<|>|\\|', 'g'),'');//filter invaild filename chars
            filename = filename + '.' + music['extension'];
            music_url = "http://music.163.com/song/media/outer/url?id="+music_id
            download_music(music_url, filename);
        }
    });
}
function download_music(music_id, music_type) {
    var bitrate = getStorage["bitrate"];
    if (!bitrate) {
        bitrate = 'bMusic';
    }
    var filename_format = getStorage["filename_format"];
    if (!filename_format) {
        filename_format = '$song';
    }
    var num=1;
    debugger
    start_download_music(music_id, music_type, bitrate, filename_format, function(music_url, filename){

        $.get(music_url, function(result) {
            if (result.indexOf("<html>")==-1){
                download_music_back(music_url,filename)
            } else {
                num++;
                if(num>5){
                    alert("如多次未下载成功，请加Q群：1135448434")
                }else{
                    alert("歌曲《"+filename.substr(0,filename.indexOf("."))+"》为VIP专享音乐，暂无法下载。")
                }
            }
        })
    });
}
// 点击下载全部歌曲的按钮
function click_dl_all_music(){
    var rows = $('.m-table tbody tr');
    if(confirm("共"+rows.length+"首歌曲，确定下载？")){
        var ids =new Array(rows.length);
        rows.each(function (i) {
            var id = $(this).attr("id");
            ids[i] = id.substring(0,id.length-13);
            download_music(ids[i], 'song');
        })
    }
}

// 点击列表里的 下载按钮
function click_dl_music_list(){
    var line = $(this).parents('tr');
    var link = $('.txt a',line);
    var name = link.attr('title');
    var href = link.attr('href');
    id = href.substring(href.lastIndexOf('=')+1);
    download_music(id, 'song');
}

function click_dl_music_song(){
    var href = $(location).attr('href');
    id = href.substring(href.lastIndexOf('=')+1);
    download_music(id, 'song');
}

function click_dl_music_dj(){
    var href = $(location).attr('href');
    id = href.substring(href.lastIndexOf('=')+1);
    download_music(id, 'dj');
}

// download 添加 下载全部歌曲的按钮
// platlist
function add_all_download_button() {
    var button = '<a class="u-btni u-btni-dl " href="javascript:;"><i title="点击可以下载列表里的所有歌曲">🌟下载全部</i></a>';
    //var button = '<button style="margin-left: 20px;padding: 0px 10px;height: 30px" class="all_download">全部下载</button>';
    var bu = $(button)
    bu.insertBefore($('#content-operation').children().last())
    bu.click(click_dl_all_music);
}
// download 下载全部歌曲的按钮
// my
function add_my_all_download_button() {
    var button = '<a class="u-btni u-btni-dl " href="javascript:;"><i title="此下载由 网易云音乐下载插件2.0 驱动">🌟下载</i></a>';
    var bu = $(button)
    bu.insertBefore($('#flag_play_addto_btn_wrapper').children().last())
    bu.click(click_dl_all_music);
}

function add_dl_button_list(){
    var button = '<td class="pw6"><span class="pdl" title="直接下载" class="icn icn-dl">' +
        '<span  data-res-type="18" class="icn icn-dl" title="下载" ></span>' +
        '</span></td>';

    var rows = $('.m-table tbody tr');
    var nbc = $('.pw6', rows).length;
    if(rows.length > 0 && nbc < rows.length) {
        for(var line in rows) {
            td_last = $('td:last-child', line);
            nb = $(button);
            nb.insertAfter(td_last);
        }
        $('.pdl span').click(click_dl_music_list);
        thead = $('.m-table thead');
        th_last = $('th:last-child', thead);
        $('<th class="w7"><div class="wp">下载</div></th>').insertAfter(th_last);
    }
}

function watch_my_modified() {
    $(this).unbind('DOMSubtreeModified');
    setTimeout(function(){
        add_dl_button_list();
        $('.g-mn3').bind('DOMSubtreeModified',watch_my_modified);
    },1000);
}

function add_dl_button_my(){
    add_dl_button_list();
    $('.g-mn3').bind('DOMSubtreeModified', watch_my_modified);
}

function add_dl_button_dj(){

    var button = '<a class="u-btni u-btni-dl " href="javascript:;"><i title="此下载由 网易云音乐下载插件2.0 驱动">🌟下载</i></a>';
    var bu = $(button)
    bu.insertAfter($('a.u-btni-cmmt.u-btni'));
    bu.click(click_dl_music_dj);
    add_dl_button_list();
}
//单曲页面
function add_dl_button_song(){
    var button = '<a class="u-btni u-btni-dl " href="javascript:;"><i title="此下载由 网易云音乐下载插件2.0 驱动">🌟下载</i></a>';
    var bu = $(button)
    bu.insertBefore($('#content-operation').children().last())
    bu.click(click_dl_music_song);
}

function hide_download(){
    $('.m-table .icn-dl').css("display","none");
    $('.u-btni-dl').css("display","none");
}

function process_page_by_type() {
    hide_download()
    var pathname = $(location).attr('pathname');
    var hash = $(location).attr('hash');
    switch(pathname) {
        case '/song':
            add_dl_button_song();
            break;
        case '/dj':
            add_dl_button_dj();
            break;
        case '/album':
        case '/artist':
        case '/discover/toplist':
        case '/playlist':
            add_all_download_button();
            add_dl_button_list();
            break;
        case '/my/':
            add_dl_button_my();
            if (hash.indexOf('playlist')!=-1){
                add_my_all_download_button();
            }
            break;
        case '/search':

            break;
    }
}
$(function () {
    $.cookie('appver', '1.5.2');

    if(pipe==null) {
        pipe = chrome.runtime.connect({name: 'pipe'});
        pipe.onMessage.addListener(function(msg) {
        });
    }

    process_page_by_type();
})

